package com.jlnk.okhttpdemo.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.jlnk.okhttpdemo.R;
import com.jlnk.okhttpdemo.entity.HotSearchItem;
import java.util.List;

public class HotSearchAdapter extends RecyclerView.Adapter<HotSearchAdapter.ViewHolder> {
    private List<HotSearchItem> items;
    private Context context;

    public HotSearchAdapter(Context context) {
        this.context = context;
    }

    public void setItems(List<HotSearchItem> items) {
        this.items = items;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_hot_search, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        HotSearchItem item = items.get(position);
        holder.title.setText(item.getTitle());
        holder.hotValue.setText(item.getHotValue());
        holder.itemView.setOnClickListener(v -> {
            String url = item.getLink();
            if (url != null) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return items == null ? 0 : items.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;
        TextView hotValue;

        ViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            hotValue = itemView.findViewById(R.id.hotValue);
        }
    }
}